<template>
  <div style="display: flex; flex-direction: column; height: 100%" v-if="isComponentMounted">
    <div class="header">
      <button class="back-button" @click="handleBack">返回</button>
      <span class="title">产品生产装配碳排放值收集 / {{ materialOrProductName }}</span>
      <div class="header-buttons">
        <el-button type="primary" link :icon="CirclePlus" @click="openAllocationWindow" v-if="typeId === '2'"
          >设定分配数据</el-button
        >
        <el-button type="primary" link :icon="Document" @click="save">保存</el-button>
      </div>
    </div>
    <div style="position: relative; flex: 1; overflow: hidden">
      <allocation-window ref="allocationWindowRef" />
      <!-- 输入弹出窗口 -->
      <el-dialog v-model="isInputModalOpen" title="输入" width="400px">
        <el-form :model="inputForm" :rules="inputRules" ref="inputRuleFormRef" style="margin-top: 20px">
          <el-form-item label="能源类型" prop="source" :label-width="formLabelWidth">
            <el-select v-model="inputForm.source" placeholder="请选择能源类型">
              <el-option v-for="item in factorType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!-- 绑定设备选择 -->
          <el-form-item label="绑定设备" prop="equipmentId" :label-width="formLabelWidth">
            <el-select v-model="inputForm.equipmentId" placeholder="请选择设备">
              <el-option v-for="item in inputEquipmentOptions" :key="item.id" :label="item.equipmentName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="isInputModalOpen = false">取消</el-button>
            <el-button type="primary" @click="addInputNode()"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 输出弹出窗口 -->
      <el-dialog v-model="isOutputModalOpen" title="输出" width="400px">
        <el-form :model="outputForm" :rules="outputRules" ref="outputRuleFormRef" style="margin-top: 20px">
          <el-form-item label="输出类型" prop="output" :label-width="formLabelWidth">
            <el-select v-model="outputForm.output" placeholder="请选择输出类型">
              <el-option v-for="item in outputType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="输出名称" prop="label" :label-width="formLabelWidth">
            <el-input v-model="outputForm.label" placeholder="请输入输出名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="isOutputModalOpen = false">取消</el-button>
            <el-button type="primary" @click="addOutputNode()"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 设备绑定弹窗（查看详情） -->
      <el-dialog v-model="isDetailOpen" title="查看详情" width="860px" :close-on-click-modal="false">
        <!-- 只读信息 -->
        <el-descriptions :column="1" size="default" border>
          <el-descriptions-item label="工序编号" :label-style="{ width: '80px' }">
            {{ detailForm.processId }}
          </el-descriptions-item>

          <el-descriptions-item label="工序名称" :label-style="{ width: '80px' }">
            {{ detailForm.processName }}
          </el-descriptions-item>

          <el-descriptions-item label="工序描述" :label-style="{ width: '80px' }">
            {{ detailForm.description }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 所属设备 -->
        <h4 style="margin: 20px 0 10px; font-weight: 600">所属设备</h4>

        <!-- 设备绑定表格 -->
        <el-table
          :data="equipmentBindings"
          style="width: 100%"
          max-height="400px"
          border
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', height: '50px', fontWeight: 600 }"
          :cell-style="{ height: '45px' }"
          ref="equipTable"
          @header-dragend="equipTable!.doLayout()"
        >
          <el-table-column type="index" label="序号" align="center" min-width="60" />
          <el-table-column label="设备名称" align="center" min-width="180">
            <template #default="{ row }">
              <el-select
                v-model="row.equipmentId"
                placeholder="选择设备"
                filterable
                remote
                :remote-method="queryEquipments"
                style="width: 180px"
              >
                <el-option v-for="item in equipmentOptions" :key="item.id" :label="item.equipmentName" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" min-width="100">
            <template #default="{ $index }">
              <el-button link type="danger" @click="removeBinding($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 10px">
          <!-- 添加设备按钮：最多两条 -->
          <el-button type="primary" link @click="addBinding" :disabled="equipmentBindings.length >= 2">+ 添加所属设备</el-button>

          <!-- 右侧操作按钮 -->
          <div>
            <el-button @click="isDetailOpen = false">取消</el-button>
            <el-button type="primary" @click="confirmBindings">确认</el-button>
          </div>
        </div>
      </el-dialog>
      <!-- 输入节点详情编辑对话框 -->
      <el-dialog v-model="inputNodeDetailDialogVisible" title="详情" width="500px" :close-on-click-modal="false">
        <el-form :model="inputNodeForm" label-width="100px">
          <el-form-item label="能源类型">
            <el-select v-model="inputNodeForm.source" placeholder="请选择能源类型" style="width: 100%">
              <el-option v-for="item in factorType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="绑定设备">
            <el-select v-model="inputNodeForm.equipmentId" placeholder="请选择绑定设备" style="width: 100%">
              <el-option v-for="item in inputEquipmentOptions" :key="item.id" :label="item.equipmentName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="inputNodeDetailDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updateInputNodeDetail">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <div class="process-flow-container">
        <VueFlow
          v-model:nodes="nodes"
          v-model:edges="edges"
          :default-viewport="{ x: 0, y: 0, zoom: 1 }"
          fit-view-on-init
          class="confirm-flow"
          :min-zoom="0.2"
          :max-zoom="4"
          :nodes-draggable="false"
          :fit-view-options="{ padding: 0.2 }"
        >
          <Background color="#3eaea4" />
          <template #node-default="props">
            <toolBarDefault :id="props.id" :data="props.data" @toolbar-action="handleToolbarAction" />
          </template>
          <template #node-output="props">
            <toolBarInput :id="props.id" :data="props.data" @toolbar-action="handleToolbarAction" />
          </template>
          <template #node-input="props">
            <toolBarOutput :id="props.id" :data="props.data" @toolbar-action="handleToolbarAction" />
          </template>
        </VueFlow>
      </div>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { onMounted, onBeforeUnmount, reactive, ref, watch } from "vue";
import { VueFlow, type Node, type Edge } from "@vue-flow/core";
import { Background } from "@vue-flow/background";
import toolBarDefault from "@/views/proTable/components/toolBarDNode.vue";
import toolBarInput from "@/views/proTable/components/toolBarINode.vue";
import toolBarOutput from "@/views/proTable/components/toolBarONode.vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { Document, CirclePlus } from "@element-plus/icons-vue";
import { factorType, outputType } from "@/utils/serviceDict";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";
import AllocationWindow from "./components/allocationWindow.vue";
import { useTabsStore } from "@/stores/modules/tabs";
const tabStore = useTabsStore();

import {
  createNewNode,
  createNewEdge,
  initializeFlowChart,
  realignIONodes,
  initializeIONodes,
  saveFlowChart
} from "@/utils/flowPositionHandler";

import { ElTable } from "element-plus";
const equipTable = ref<InstanceType<typeof ElTable> | null>(null);
// 设备映射：id -> name
const equipmentNameMap = ref<Record<number, string>>({});

const formLabelWidth = "80px";
const currentNodeId = ref<string | null>(null); // 当前操作的节点 ID
const nodes = ref<Node[]>([]);
const edges = ref<Edge[]>([]);
const route = useRoute();
const router = useRouter();
const projectId = route.params.projectId as string;
const typeId = route.params.typeId as string;
const id = route.params.id as string;
const allocationWindowRef = ref<InstanceType<typeof AllocationWindow> | null>(null);
// 后端获取的流程图数据列表
const flowChartList = ref<any[]>([]);
// 后端基础地址
const baseUrl = import.meta.env.VITE_BASE_URL;
const materialOrProductName = ref<string>("");
const inputRuleFormRef = ref<FormInstance>();
const outputRuleFormRef = ref<FormInstance>();
const inputForm = reactive({
  source: "", // 能源类型
  equipmentId: "" // 绑定设备
});

// 输入弹窗绑定设备下拉选项
const inputEquipmentOptions = ref<any[]>([]);
const outputForm = reactive({
  output: "",
  label: ""
});
const detailForm = reactive({
  processId: "", // 工艺编号
  processName: "", // 工艺名称
  equipmentName: "", // 所属设备
  description: "", // 工艺描述
  title: "" // 标题
});

// 设备绑定数据与合计
const equipmentBindings = ref<any[]>([]);
const isComponentMounted = ref(false);
const isDataProcessing = ref(false); // 添加数据处理状态标志

const inputRules = reactive({
  source: [{ required: true, message: "请选择能源类型", trigger: "blur" }],
  equipmentId: [{ required: true, message: "请选择绑定设备", trigger: "blur" }]
});
const outputRules = reactive({
  output: [{ required: true, message: "请选择输出类型", trigger: "blur" }], // 输出类型
  label: [{ required: true, message: "请输入输出名称", trigger: "blur" }] // 输出名称
});

const isInputModalOpen = ref(false);
const isOutputModalOpen = ref(false);
const isDetailOpen = ref(false);
// 添加输入节点详情对话框控制
const inputNodeDetailDialogVisible = ref(false);
const inputNodeForm = reactive({
  source: "",
  equipmentId: ""
});

const addInputNode = () => {
  inputRuleFormRef.value!.validate(async valid => {
    if (!valid) return;
    const currentNode = nodes.value.find(node => node.id === currentNodeId.value);
    if (!currentNode) {
      ElMessage.error("未找到对应的节点！");
      return;
    }

    const newNodeId = (Math.max(...nodes.value.map(node => parseInt(node.id))) + 1).toString();

    const equipId = Number(inputForm.equipmentId);
    const equipName = equipmentNameMap.value[equipId] || `设备${equipId}`;

    const newNode = createNewNode(newNodeId, "output", {
      label: inputForm.source,
      isEmission: 1,
      output: inputForm.source,
      equipmentId: equipId,
      equipmentName: equipName
    });

    // 使用 handler 创建新边
    const newEdge = createNewEdge(newNodeId, currentNodeId.value || "");

    nodes.value.push(newNode);
    edges.value.push(newEdge);

    // 重新计算所有节点位置
    realignIONodes(nodes.value, edges.value, currentNodeId.value || "");

    inputForm.source = "";
    inputForm.equipmentId = "";
    isInputModalOpen.value = false;
  });
};

const addOutputNode = () => {
  outputRuleFormRef.value!.validate(async valid => {
    if (!valid) return;
    const currentNode = nodes.value.find(node => node.id === currentNodeId.value);
    if (!currentNode) {
      ElMessage.error("未找到对应的节点！");
      return;
    }

    const newNodeId = (Math.max(...nodes.value.map(node => parseInt(node.id))) + 1).toString();

    // 使用 handler 创建新节点
    const newNode = createNewNode(newNodeId, "input", {
      label: outputForm.label,
      isEmission: 1,
      output: outputForm.output,
      outputLabel: outputForm.label
    });

    // 使用 handler 创建新边
    const newEdge = createNewEdge(currentNodeId.value || "", newNodeId);

    nodes.value.push(newNode);
    edges.value.push(newEdge);

    // 重新计算所有节点位置
    realignIONodes(nodes.value, edges.value, currentNodeId.value || "");

    outputForm.output = "";
    outputForm.label = "";
    isOutputModalOpen.value = false;
  });
};

const initializeNodesAndEdges = async () => {
  isDataProcessing.value = true;

  try {
    if (typeId === "0") {
      await initializeAssemblyProcess();
    } else if (typeId === "1") {
      await initializeMaterialProcess();
    }

    // 初始化输入输出节点
    const { nodes: updatedNodes, edges: updatedEdges } = initializeIONodes(
      projectId,
      typeId,
      id,
      nodes.value,
      edges.value,
      flowChartList.value,
      { isProcessFlow: false }
    );

    nodes.value = updatedNodes;
    edges.value = updatedEdges;
  } catch (error) {
    console.error("初始化节点和边时出错:", error);
    ElMessage.error("初始化失败");
  } finally {
    isDataProcessing.value = false;
  }
};

// 获取装配流程数据（按项目过滤，objectType 固定为 0 => 装配流程）
const fetchAssemblyProcesses = async (projId: number) => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getProjectProcessesEquipment`, {
      params: { projectId: projId }
    });
    console.log("获取装配流程数据:", res.data);
    if (res.data?.code === 200) {
      return res.data.data || [];
    }
    ElMessage.warning(res.data?.msg || "获取装配流程数据失败");
    return [];
  } catch (error) {
    console.error("获取装配流程数据失败:", error);
    ElMessage.error("获取装配流程数据失败");
    return [];
  }
};

// 从后端获取项目信息
// const fetchProjectDetails = async (projectId: string) => {
//   try {
//     const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
//     const userId = Number(userInfo.id) || 0;

//     const res = await axios.post(`${baseUrl}/api/carbon/getProjectById?projectId=${projectId}`, {
//       userId: userId
//     });
//     console.log("从后端获取项目信息:", res.data);
//     if (res.data?.code === 200) {
//       return res.data.data;
//     }
//     ElMessage.warning(res.data?.msg || "获取项目信息失败");
//     return null;
//   } catch (error) {
//     console.error("获取项目信息失败:", error);
//     ElMessage.error("获取项目信息失败");
//     return null;
//   }
// };

// 初始化装配流程
const initializeAssemblyProcess = async () => {
  // 获取项目信息
  // const projectInfo = await fetchProjectDetails(projectId);
  // if (!projectInfo) {
  //   return;
  // }
  // const productId = projectInfo.productId;
  // if (!productId) {
  //   ElMessage.warning("项目未关联产品");
  //   return;
  // }
  const processData = await fetchAssemblyProcesses(Number(projectId));
  if (processData.length === 0) {
    nodes.value = [];
    edges.value = [];
    return;
  }

  const { nodes: newNodes, edges: newEdges } = initializeFlowChart(processData, {
    spacing: 170,
    isEmission: 1
  });
  nodes.value = newNodes;
  edges.value = newEdges;
};

// 初始化物料流程
const initializeMaterialProcess = async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const userId = Number(userInfo.id) || 0;
  const materialId = Number(id);

  // 获取物料详情
  await fetchMaterialDetail(userId, materialId);
  // 获取物料工序数据
  const processes = await fetchMaterialProcesses(materialId);

  if (processes.length === 0) {
    nodes.value = [];
    edges.value = [];
    return;
  }

  // 初始化节点和边
  const { nodes: newNodes, edges: newEdges } = initializeFlowChart(processes, {
    spacing: 170,
    isEmission: 1
  });

  nodes.value = newNodes;
  edges.value = newEdges;
};

// 获取物料详情
const fetchMaterialDetail = async (userId: number, materialId: number) => {
  try {
    const detailRes = await axios.post(`${baseUrl}/api/carbon/getMaterialById?materialId=${materialId}`, {
      userId: userId
    });
    if (detailRes.data?.code === 200) {
      materialOrProductName.value = detailRes.data.data?.materialName || "";
    }
  } catch (error) {
    console.error("获取物料详情失败", error);
  }
};

// 获取物料工序数据
const fetchMaterialProcesses = async (materialId: number) => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getMaterialProcessesEquipment`, {
      params: { projectId, materialId }
    });
    console.log("获取物料流程(含设备):", res.data);
    if (res.data?.code === 200) {
      return res.data.data || [];
    }
    ElMessage.warning(res.data?.msg || "获取物料流程数据失败");
    return [];
  } catch (error) {
    console.error("获取物料流程数据失败:", error);
    ElMessage.error("获取物料流程数据失败");
    return [];
  }
};

const openInputModal = async () => {
  const currentNode = nodes.value.find(node => node.id === currentNodeId.value);
  if (!currentNode) {
    ElMessage.error("未找到对应的节点！");
    return;
  }

  // 保证映射表最新
  await queryEquipments("");

  // 从当前默认节点的 data.equipments 中提取设备列表
  const equips = currentNode.data.equipments || [];
  inputEquipmentOptions.value = equips.map((e: any) => {
    const idNum = Number(e.equipmentId);
    return {
      id: idNum,
      equipmentName: equipmentNameMap.value[idNum] || `设备${idNum}`
    };
  });

  isInputModalOpen.value = true;
  inputForm.source = "";
  inputForm.equipmentId = "";
  if (inputRuleFormRef.value) {
    inputRuleFormRef.value.clearValidate();
  }
};

const openOutputModal = () => {
  isOutputModalOpen.value = true;
  outputForm.output = "";
  outputForm.label = "";
  if (outputRuleFormRef.value) {
    outputRuleFormRef.value.clearValidate();
  }
};

const openDetailModal = () => {
  isDetailOpen.value = true;
};

const openAllocationWindow = () => {
  if (allocationWindowRef.value) {
    allocationWindowRef.value.openDialog({
      projectId,
      typeId,
      id
    });
  }
};

const handleToolbarAction = async (action: string, nodeId: string, type?: string) => {
  currentNodeId.value = nodeId;
  console.log("Toolbar action:", action, "Node ID:", nodeId, "Type:", type);

  if (action === "添加输入") {
    openInputModal();
  } else if (action === "添加输出") {
    openOutputModal();
  } else if (action === "详情") {
    const currentNode = nodes.value.find(node => node.id === nodeId);
    if (!currentNode) return;

    // ------------- 生成绑定设备下拉选项 -------------
    // 保证设备映射最新
    await queryEquipments("");

    // 查找当前输入节点所连接的默认（工序）节点
    const edge = edges.value.find(e => e.source === nodeId || e.target === nodeId);
    let defaultNode: Node | undefined;
    if (edge) {
      const defaultNodeId = edge.source === nodeId ? edge.target : edge.source;
      defaultNode = nodes.value.find(n => n.id === defaultNodeId);
    }

    if (defaultNode && defaultNode.data?.equipments) {
      inputEquipmentOptions.value = (defaultNode.data.equipments || []).map((e: any) => {
        const idNum = Number(e.equipmentId);
        return {
          id: idNum,
          equipmentName: equipmentNameMap.value[idNum] || `设备${idNum}`
        };
      });
    } else {
      // 回退全部设备
      inputEquipmentOptions.value = equipmentOptions.value.map((item: any) => ({
        id: item.id,
        equipmentName: item.equipmentName
      }));
    }

    // 确保当前节点绑定的设备在选项中，否则添加进去，避免初始显示为编号
    const currentEquipId = Number(currentNode.data.equipmentId);
    if (currentEquipId && !inputEquipmentOptions.value.some(opt => Number(opt.id) === currentEquipId)) {
      inputEquipmentOptions.value.push({
        id: currentEquipId,
        equipmentName: equipmentNameMap.value[currentEquipId] || `设备${currentEquipId}`
      });
    }
    // --------------------------------------------------

    // 初始化表单
    inputNodeForm.source = currentNode.data.label || "";
    inputNodeForm.equipmentId =
      Number(currentNode.data.equipmentId) || (inputEquipmentOptions.value.length ? inputEquipmentOptions.value[0].id : "");
    inputNodeDetailDialogVisible.value = true;
  } else if (action === "查看详情") {
    const currentNode = nodes.value.find(node => node.id === nodeId);
    if (!currentNode) return;

    // 工序节点详情
    // 先加载全部设备列表，保证 select 有对应 label
    await queryEquipments("");

    detailForm.processId = currentNode.data.processId || "";
    detailForm.processName = currentNode.data.label || "";
    detailForm.description = currentNode.data.description || "";

    equipmentBindings.value = currentNode.data.equipments ? JSON.parse(JSON.stringify(currentNode.data.equipments)) : [];
    if (equipmentBindings.value.length === 0) {
      equipmentBindings.value.push({ equipmentId: "" });
    }

    // 根据设备绑定信息，设置设备名称（如果存在）
    if (equipmentBindings.value.length > 0) {
      const equip = equipmentBindings.value[0];
      const idNum = Number(equip.equipmentId);
      detailForm.equipmentName = equipmentNameMap.value[idNum] || `设备${idNum}`;
    } else {
      detailForm.equipmentName = "";
    }
    openDetailModal();
  } else if (action === "删除") {
    ElMessageBox.confirm("是否删除所选项?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    }).then(() => {
      if (type === "input") {
        deleteInputNode(nodeId);
        ElMessage.success("删除成功!");
      } else if (type === "output") {
        deleteOutputNode(nodeId);
        ElMessage.success("删除成功!");
      }
    });
  }
};

const save = () => {
  const unboundNodes = nodes.value.filter(n => n.type === "default" && (!n.data.equipments || n.data.equipments.length === 0));

  if (unboundNodes.length > 0) {
    ElMessage.warning("存在未绑定设备的工序节点，请先选择设备后再保存！");
    return;
  }

  try {
    saveFlowChart(nodes.value, edges.value, Number(projectId), typeId, id, flowChartList.value, { isProcessFlow: false });
    ElMessage.success("保存成功");
  } catch (error) {
    ElMessage.error("保存失败");
  }
};

const deleteInputNode = (nodeId: string) => {
  // 找到要删除节点的父节点
  const edge = edges.value.find(e => e.source === nodeId || e.target === nodeId);
  const parentNodeId = edge?.target === nodeId ? edge.source : edge?.target;

  // 删除节点和相关的边
  nodes.value = nodes.value.filter(node => node.id !== nodeId);
  edges.value = edges.value.filter(edge => edge.source !== nodeId && edge.target !== nodeId);

  // 重新计算剩余节点的位置
  if (parentNodeId) {
    realignIONodes(nodes.value, edges.value, parentNodeId);
  }
};

const deleteOutputNode = (nodeId: string) => {
  // 找到要删除节点的父节点
  const edge = edges.value.find(e => e.source === nodeId || e.target === nodeId);
  const parentNodeId = edge?.source === nodeId ? edge.target : edge?.source;

  // 删除节点和相关的边
  nodes.value = nodes.value.filter(node => node.id !== nodeId);
  edges.value = edges.value.filter(edge => edge.source !== nodeId && edge.target !== nodeId);

  // 重新计算剩余节点的位置
  if (parentNodeId) {
    realignIONodes(nodes.value, edges.value, parentNodeId);
  }
};

// 返回按钮处理函数
const handleBack = () => {
  const pid = route.params.projectId as string;
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/inventory/activityList/${pid}`);
};

// ====================== 获取流程图数据 ======================
const fetchFlowChartList = async () => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getFlowchart`, {
      params: { projectId, objectId: id }
    });
    console.log("获取流程图数据:", res.data);
    if (res.data && res.data.code === 200) {
      flowChartList.value = res.data.data?.nodes || [];
      console.log("flowChartList:", flowChartList.value);
    } else {
      ElMessage.error(res.data.msg || "获取流程图失败");
    }
  } catch (error) {
    console.error("获取流程图出错:", error);
    ElMessage.error("获取流程图失败");
  }
};

// 获取设备列表
const equipmentOptions = ref<any[]>([]);
const queryEquipments = async (keyword: string) => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const userId = Number(userInfo.id) || 0;

  try {
    const res = await axios.post(`${baseUrl}/api/carbon/getAllEquipments`, {
      userId
    });

    if (res.data?.code === 200) {
      const list = res.data.data || [];
      // 构建映射表：id -> name
      list.forEach((item: any) => {
        equipmentNameMap.value[item.id] = item.equipmentName;
      });

      equipmentOptions.value = keyword ? list.filter((item: any) => item.equipmentName.includes(keyword)) : list;
    } else {
      equipmentOptions.value = [];
    }
  } catch (error) {
    console.error("查询设备失败:", error);
    equipmentOptions.value = [];
  }
};

// 添加设备绑定
const addBinding = () => {
  if (equipmentBindings.value.length >= 2) {
    ElMessage.warning("最多只能绑定两个设备");
    return;
  }

  equipmentBindings.value.push({
    equipmentId: ""
  });
};

// 移除设备绑定
const removeBinding = (index: number) => {
  equipmentBindings.value.splice(index, 1);
};

// 确认设备绑定
const confirmBindings = () => {
  // 更新当前节点的数据
  const targetNode = nodes.value.find(n => n.id === currentNodeId.value);
  if (targetNode) {
    targetNode.data = {
      ...targetNode.data,
      equipments: JSON.parse(JSON.stringify(equipmentBindings.value)),
      equipmentName:
        equipmentBindings.value.length > 0
          ? (() => {
              const idNum = Number(equipmentBindings.value[0].equipmentId);
              return equipmentNameMap.value[idNum] || `设备${idNum}`;
            })()
          : ""
    };
  }
  isDetailOpen.value = false;
};

// 更新输入节点详情
const updateInputNodeDetail = () => {
  const currentNode = nodes.value.find(node => node.id === currentNodeId.value);
  if (currentNode) {
    // 将选择的能源类型转为数字类型
    const labelValue = Number(inputNodeForm.source);
    const equipIdNum = Number(inputNodeForm.equipmentId);

    // 只更新label属性为数字类型
    currentNode.data = {
      ...currentNode.data,
      label: labelValue,
      equipmentId: equipIdNum,
      equipmentName: equipmentNameMap.value[equipIdNum] || `设备${equipIdNum}`
    };

    inputNodeDetailDialogVisible.value = false;
    ElMessage.success("更新成功");
  }
};

onMounted(async () => {
  isComponentMounted.value = true;
  console.log("组件挂载，开始初始化...");
  await fetchFlowChartList();
  await initializeNodesAndEdges();
});

onBeforeUnmount(async () => {
  // 等待数据处理完成
  if (isDataProcessing.value) {
    await new Promise(resolve => {
      const unwatch = watch(isDataProcessing, newVal => {
        if (!newVal) {
          unwatch();
          resolve(true);
        }
      });
    });
  }

  isComponentMounted.value = false;
  nodes.value = [];
  edges.value = [];
});

// 添加路由进入的钩子
const init = async () => {
  console.log("重新初始化组件...");
  isComponentMounted.value = true;
  await fetchFlowChartList();
  await initializeNodesAndEdges();
};

// 监听路由变化
watch(
  () => route.fullPath,
  () => {
    if (route.name === "selfMadeEmission") {
      init();
    }
  }
);
</script>

<style>
.header {
  display: flex;

  /* 左右分布 */
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.header-buttons {
  display: flex;
  gap: 10px;
  margin-left: auto;
}
.back-button {
  padding: 8px 12px;
  margin-right: 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}
.back-button:hover {
  background-color: #007d6a;
}
.title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
}
.el-button {
  padding: 8px 12px;
  font-size: 14px;
}
.modal-content {
  z-index: 10000;
  width: 300px;
  padding: 20px;
  text-align: center;
  background: white;
  border-radius: 5px;
}
select {
  width: 100%;
  padding: 8px;
  margin: 10px 0;
  border: 1px solid #cccccc;
  border-radius: 4px;
}
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 1000;
  width: 400px;
  max-width: 90%;
  height: auto;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  transform: translate(-50%, -50%);
}
.vue-flow__node-toolbar {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  padding: 8px;
  background-color: #2d3748;
  border-radius: 8px;
  box-shadow: 0 0 10px rgb(0 0 0 / 50%);
}
.vue-flow__node-toolbar button {
  padding: 0.5rem 1rem;
  color: white;
  cursor: pointer;
  background: #4a5568;
  border: none;
  border-radius: 8px;
}
.vue-flow__node-toolbar button.selected {
  background: #009688;
}
.vue-flow__node-toolbar button:hover {
  background: #009688;
}
.vue-flow__node-default {
  padding: 20px;
  color: #009688;
  background: #e6f5f3;
  border: 1px solid #009688;
  border-radius: 4px;
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}
.vue-flow__node-default.selected {
  box-shadow: 0 0 0 0.1px #009688;
}
.vue-flow__node-output {
  width: 200px;
  padding: 8px;
  color: #0078d4;
  background: #dff5fd;
  border: 1px solid #0078d4;
  border-radius: 8px;
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}
.vue-flow__node-output.selected {
  box-shadow: 0 0 0 0.1px #0078d4;
}
.vue-flow__node-input {
  width: 200px;
  padding: 8px;
  color: #d4237a;
  background: #fff6fc;
  border: 1px solid #d4237a;
  border-radius: 8px;
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}
.vue-flow__node-input.selected {
  box-shadow: 0 0 0 0.1px #d4237a;
}
.data-source-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px;
}
.data-source-option {
  display: flex;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e6f5f3;
  border-radius: 8px;
  transition: all 0.3s;
}
.data-source-option:hover {
  border-color: #009688;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}
.source-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  margin-right: 16px;
  color: #009688;
  background: #e6f5f3;
  border-radius: 8px;
}
.source-info {
  flex: 1;
}
.source-info h4 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #303133;
}
.source-info p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
.process-flow-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 100px); /* 减去头部高度 */
}
.confirm-flow {
  width: 100%;
  height: 100%;
}

/* 确保节点容器有正确的尺寸 */
.vue-flow__container {
  width: 100%;
  height: 100%;
}

/* 确保节点视图区域正确定位 */
.vue-flow__viewport {
  width: 100%;
  height: 100%;
}

/* 仅作用于弹窗内部的 descriptions 标签列 */
.el-dialog .el-descriptions__label {
  width: 80px; /* 想要多窄改这里 */
  min-width: 80px; /* 防止被拉伸 */
  padding-right: 8px; /* 适当留一点间距 */
}
</style>
